<?php if (!defined('SYSTEM_ROOT')) {
    die('Insufficient Permissions');
}

class serverchan_utils
{
    private $conf_arr = array();

    /**
     * Get system config
     * @return bool
     */
    public function get_config()
    {
        if (!empty($this->conf_arr)) {
            return true;
        }
        $conf_arr['title'] = option::get('tieba_serverchan_title');
        $conf_arr['content'] = option::get('tieba_serverchan_content');
        //check config
        if (empty($conf_arr['title'])) {
            return false;
        }
        //deal config
        $conf_arr['title'] = $this->deal_public_template($conf_arr['title']);
        $conf_arr['content'] = $this->deal_public_template($conf_arr['content']);
        $this->conf_arr = $conf_arr;
        return true;
    }

    /**
     * push notice msg
     * @param string $key key
     * @param string $title title
     * @param string $content content
     * @return json
     */
    public function push_notice($key, $title, $content)
    {
        if (empty($title) || empty($key)) {
            return array('code' => 1, 'msg' => 'KEY或标题不能为空！');
        }
        $postdata = http_build_query(
            array(
                'text' => $title,
                'desp' => $content
            )
        );

        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($opts);
        $res = json_decode(file_get_contents('https://sc.ftqq.com/'.$key.'.send', false, $context), true);
        if ($res['errno'] === 0) {
            return array('code' => 0, 'msg' => '推送成功');
        } else {
            return array('code' => 1, 'msg' => '推送失败: ' . strval($content));
        }
    }

    public function get_sign_results($user) {
        global $m;
        global $i;
        $userinfo = $m->fetch_array($m->query('select * from `' . DB_NAME . '`.`' . DB_PREFIX . 'users` where `name` = "' . $user . '"'));
        if ($i['opt']['core_version'] >= 4.0) {
            $zt = 'latest';
        } else {
            $zt = 'lastdo';
        }

        $out_put_str = '|最近签到日期|吧名|状态|备注|' . PHP_EOL . '|:---:|:---:|:---:|:---:|' . PHP_EOL;
        $query = $m->query("SELECT * FROM  `" . DB_NAME . "`.`" . DB_PREFIX . "tieba` WHERE `uid`=" . $userinfo['id']);
        while ($tieba = $m->fetch_array($query)) {
            $tieba_count++;
            if ((date("Y-m-") . $tieba[$zt] == date("Y-m-j", strtotime("-1 day"))) || empty($tieba[$zt])) {
                $status_str = '未签';
                $status_icon = '？ ';
                $msg = '-';
            } elseif (!empty($tieba['no'])) {
                $status_str = '忽略';
                $status_icon = 'i ';
                $msg = '-';
            } elseif ($tieba['status'] == 0) {
                $status_str = '成功';
                $status_icon = '✔ ';
                $msg = '-';
            } else {
                $status_str = '失败';
                $status_icon = '✘ ';
                $msg = $tieba['last_error'];
            }
            $out_put_str .= '|' . ($tieba[$zt] ? date("Y/m/") . $tieba[$zt] : '-');
            $out_put_str .= '|' . $tieba['tieba'];
            $out_put_str .= '|' . $status_icon . $status_str;
            $out_put_str .= '|' . $msg . '|' . PHP_EOL;
        }
        if (empty($tieba_count)) {
            return '没有关注的贴吧！请添加关注贴吧后在【云签到设置和日志】中刷新贴吧列表！';
        }
        return PHP_EOL . $out_put_str . PHP_EOL;
    }

    /**
     * Deal the template,replace the user variable
     * @param string $template_str
     * @param string $user_name
     * @return mixed
     */
    public function deal_user_template($template_str, $user_name)
    {
        $user_pattern_arr = array(
            '/\[name\]/',
            '/\[details\]/'
        );
        $user_replacement_arr = array(
            $user_name,
            $this->get_sign_results($user_name)
        );
        return $this->deal_public_template(strval(preg_replace($user_pattern_arr, $user_replacement_arr, $template_str)));
    }

    /**
     *  Deal the template,replace the public variable
     * @param string $template_str
     * @return mixed
     */
    private function deal_public_template($template_str)
    {
        $public_pattern_arr = array(
            '/\[date\]/',
            '/\[SYSTEM_URL\]/',
            '/\[SYSTEM_NAME\]/',
        );
        $public_replacement_arr = array(
            date('Y-m-d'),
            SYSTEM_URL,
            SYSTEM_NAME,
        );
        return preg_replace($public_pattern_arr, $public_replacement_arr, $template_str);
    }
}
